package de.dopichaj.labrador.search.erg;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

import de.dopichaj.labrador.search.QueryCategory;
import de.dopichaj.labrador.search.hit.CategorizedHit;
import de.dopichaj.labrador.search.hit.HitUpdateTable;


public final class ErgScoreUpdater {
    
    private static final Logger log = Logger.getLogger(ErgScoreUpdater.class);
    
    private final ElementRelationshipGraph erg;
    private final Collection<QueryCategory> categories;
    
    public ErgScoreUpdater(ElementRelationshipGraph erg,
        Collection<QueryCategory> categories) {
        this.categories = categories;
        this.erg = erg;
    }
    
    /**
     * Obtains the hits' global scores based on their category scores.
     */
    public void performSimilarityCalculation(Collection<CategorizedHit> hits) {
        HitUpdateTable hitUpdateTable = new HitUpdateTable(hits);
        for (QueryCategory category : categories) {
            performSimilarityCalculation(category, hits, hitUpdateTable);
        }
        log.debug("Finished similarity calculation");
        mergeSimilarityLists(hits);
    }
    
    /**
     * Performs the element similarity calculation on a list of hits for a given category.
     */
    private void performSimilarityCalculation(QueryCategory category,
        Collection<CategorizedHit> hits, HitUpdateTable hitUpdateTable) {
        
        if(log.isDebugEnabled()) {
            log.debug("Performing similarity calculation for category " + category);
        }        
        
        if (category == null || category.getName().equals(""))
            return;
        
        ErgNode node = erg.lookupNode(category.getName());
        
        Set<ErgNode> elementsInCategory = node.getNodesInCategory();

        Set<CategorizedHit> processedHits = new HashSet<CategorizedHit>();
        performRecursiveSimilarityCalculation(category, node,
            elementsInCategory, processedHits, hits, hitUpdateTable);
        for (CategorizedHit hit : hits) {
            if (!processedHits.contains(hit)) {
                hit.setCategoryScore(category,
                    (float)erg.getScoreUnprocessedHit(
                        hit.getCategoryScore(category)));
            }
        }
        
        log.debug("Done with similarity calculation");
    }

    /**
     * Called by performSimilarityCalculation(String, Set). A recursive
     * function that performs similarity calculation on the hits and continues
     * as long as broadening the categories makes sense.
     * 
     * @param category
     *            The category in question.
     * @param elementsInCategory
     *               The elements in the given category.
     * @param processedHits
     *            the hits that have already been processed (may be modified).
     */
    private void performRecursiveSimilarityCalculation(
        QueryCategory originalCategory, ErgNode category,
        Set<ErgNode> elementsInCategory, Set<CategorizedHit> processedHits,
        Collection<CategorizedHit> hits, HitUpdateTable hitUpdateTable) {

        if (elementsInCategory.size() == 0) {
            return;
        }
        double coherenceValue = category.coherence();
        
        boolean allHitsProcessed = true;

        for (CategorizedHit hit : hits) {

            if (hit.getCategoryScore(originalCategory) == 0 ||
                processedHits.contains(hit))
                continue;

            String xPath = hit.getXPath();
            if (isItemEmbedded(xPath, elementsInCategory)) {
                if (log.isDebugEnabled()) {
                    log.debug("Item is embedded: " +
                        hit + ", " + elementsInCategory + "," + coherenceValue);
                }
                hitUpdateTable.updateScoresAlongPath(hit, coherenceValue,
                    originalCategory, processedHits);
                processedHits.add(hit);
            } else {
                allHitsProcessed = false;
            }
        }

        if (!allHitsProcessed) {
            ErgNode broaderCategory = category.getAncestorWithMaxCoherence();
            if (log.isDebugEnabled()) {
                log.debug("Broadening \"" + category + "\" to \""
                        + broaderCategory + "\"");
            }
            performRecursiveSimilarityCalculation(
                originalCategory, broaderCategory,
                erg.getElementsInCategory(broaderCategory, category),
                processedHits, hits, hitUpdateTable);
        }
    }

    /**
     * Determine if a given path contains one from a set of elements.
     */
    private static boolean isItemEmbedded(String path, Set<ErgNode> elements) {
        for (ErgNode element : elements) {
            if (path.indexOf("/"+element.name()+"[") > -1) {
                return true;
            }
        }
        return false;
    }

    /**
     * Calculates a global similarity for hits from different categories.
     * Currently implemented as: Sum of all single scores multiplied by the
     * category weights; divided by the sum of all category weights; multiplied
     * by the number of the categories in which this hit has a score.
     */
    private void adjustGlobalSimilarity(CategorizedHit hit, double denominator) {
        if (log.isDebugEnabled()) {
            log.debug("Calculating global similarity for: " + hit);
        }
        double score = 0.0d;

        for (QueryCategory category : categories) {
            
            score += hit.getCategoryScore(category) * category.getWeight();
        }

        score = (score / denominator) * categories.size();

        hit.setScore((float)score);        
    }

    /**
     * Determine the single score of a Hit from the category scores.
     * @param hits Collection of hits with multiple categories per hit (will be modified).
     */
    private void mergeSimilarityLists(Collection<CategorizedHit> hits) {
        log.debug("Merging similarity lists...");

        double denominator = 0.0;
        for (QueryCategory category : categories) {
            denominator += category.getWeight();
        }
        
        for (CategorizedHit hit : hits) {
            adjustGlobalSimilarity(hit, denominator);
        }

        if (log.isDebugEnabled()) {
            log.debug("Finished merging similarity lists (" +
                hits.size() + " total hits).");
        }

    }
}
/*
Copyright (c) 2005 Benedikt Eger
Copyright (c) 2005-2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/